import type { CompanyUserAddRequest, UserSearchResult } from "@/api/siderBar/model";
import { getSettingGetdepartments } from "@/api/siderBar/setting";
import { deleteUserDeletecompanyuserId, postUserAddcompanyuser, postUserUpdatecompanyuserId } from "@/api/siderBar/user";
import { isSetValue } from "@/utils/helper";
import { message, Modal } from "ant-design-vue";

type FormState = CompanyUserAddRequest
type TriggerAction = "create" | "update"
export function useActionEmployee(afterSubmit?: IFn) {
  const triggerAction = ref<TriggerAction>("create")
  const actionEntry = ref<INullable<UserSearchResult>>(null)
  const {
    formRef,
    formState,
    rules,
    handleFormSubmit,
    formLoading,
    clearValidate,
    resetFormState
  } = useFormState<FormState>({
    getInitialState: getInitialFormState,
    rules: {
      name: { required: true },
      mobile: [
        { required: true },
        { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '手机号格式错误' }
      ],
      departmentId: [
        { required: true, message: "请选择所属部门" },
      ],
      position: [
        { required: true, message: "请输入岗位名称" },
      ],
      isAdmin: [
        { required: true },
      ]
    }
  })
  const { state: showActionPopup, on: openActionPopup, off: closeActionPopup } = useSwitch(false)

  const { openActionSuccess, ...rest } = useSuccessInfo()

  const roleOptions: IOption<boolean>[] = [
    { value: true, label: '管理员' },
    { value: false, label: '普通员工' },
  ]
  const { loading: pending, refreshAsync: refreshDeps, data: departments } = useRequest(() => getSettingGetdepartments(), { initialData: [] })
  useEffectScope(() => {
    watch(showActionPopup, () => {
      if (!showActionPopup.value) {
        clearValidate()
        resetFormState()
      }
    })
  })
  function getInitialFormState(): FormState {
    return {
      isAdmin: false,
      mobile: "",
      name: "",
    }
  }
  function handleTriggerAction<A extends TriggerAction>(action: A, toBeAction: A extends "update" ? UserSearchResult : null) {
    triggerAction.value = action
    actionEntry.value = toBeAction
    populateFormState()
    openActionPopup()
  }
  function populateFormState() {
    if (triggerAction.value === "update" && actionEntry.value) {
      const patch = actionEntry.value
      if (patch.name) {
        formState.value.name = patch.name
      }
      if (patch.mobile) {
        formState.value.mobile = patch.mobile
      }
      if (isSetValue(patch.departmentId)) {
        formState.value.departmentId = patch.departmentId
      }
      if (isSetValue(patch.position)) {
        formState.value.position = patch.position
      }
      if (isSetValue(patch.isAdmin)) {
        formState.value.isAdmin = patch.isAdmin
      }
    }
  }
  function resetState() {
    closeActionPopup()
    triggerAction.value = "create"
    actionEntry.value = null
  }
  async function handleSubmit() {
    const create = triggerAction.value === "create"
    let params: INullable<CompanyUserAddRequest> = null
    await handleFormSubmit(formState => {
      params = toValue(formState)
      return (create ? postUserAddcompanyuser(params) : postUserUpdatecompanyuserId(actionEntry.value!.id!, params))
    })
    resetState()
    openActionSuccess({
      title: create ? '添加成功' : '编辑成功',
      departmentName: departments.value?.find(l => l.value === params!.departmentId)?.label!,
      name: params!.name,
      roleName: roleOptions.find(l => l.value === params!.isAdmin)?.label!
    }, () => {
      afterSubmit?.()
    })
  }
  function handleUnbind(id: number) {
    Modal.confirm({
      title: '确认提示',
      content: '确认要解绑吗？',
      async onOk() {
        await deleteUserDeletecompanyuserId(id)
        message.success('操作成功')
        afterSubmit?.()
      },
    });
  }
  return {
    showActionPopup,
    formRef,
    formState,
    rules,
    roleOptions,
    handleTriggerAction,
    triggerAction,
    handleSubmit,
    pending,
    departments,
    refreshDeps,
    handleUnbind,
    formLoading,
    ...rest,
    actionEntry
  }
}
function useSuccessInfo() {
  let _afterClose: INullable<IFn> = null;
  const { state: showActionSuccess, on, off } = useSwitch(false)
  const successInfo = ref(getInitialSuccessInfo())
  function getInitialSuccessInfo() {
    return {
      title: "",
      name: "",
      departmentName: "",
      roleName: ""
    }
  }
  function openActionSuccess(data: ReturnType<typeof getInitialSuccessInfo>, afterClose: IFn) {
    Object.assign(successInfo.value, data)
    on()
    _afterClose = afterClose
  }
  function closeActionSuccess() {
    off()
    successInfo.value = getInitialSuccessInfo()
    _afterClose?.()
    _afterClose = null
  }
  return {
    successInfo,
    showActionSuccess,
    openActionSuccess,
    closeActionSuccess
  }
}